package com.suncky.frame.utils.permission;

import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PermissionFragment extends Fragment {

    private final Map<Integer, PermissionUtil.PermissionCallback> callbacks = new HashMap<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    void requestPermissions(int requestCode, @NonNull String[] permissions, @Nullable PermissionUtil.PermissionCallback callback) {
        callbacks.put(requestCode, callback);
        this.requestPermissions(permissions, requestCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.PermissionCallback callback = callbacks.remove(requestCode);
        if (callback == null) {
            return;
        }
        if (permissions.length == 0 || grantResults.length == 0) {
            callback.onResult(requestCode, new ArrayList<>(), new ArrayList<>());
            return;
        }
        List<String> granted = new ArrayList<>();
        List<String> denied = new ArrayList<>();
        for (int i = 0; i < permissions.length; ++i) {
            switch (grantResults[i]) {
                case PackageManager.PERMISSION_GRANTED:
                    granted.add(permissions[i]);
                    break;
                case PackageManager.PERMISSION_DENIED:
                    denied.add(permissions[i]);
                    break;
            }
        }
        callback.onResult(requestCode, granted, denied);
    }
}
